<template>
  <div class="admin-management">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span style="font-size: 18px; font-weight: bold">管理员管理</span>
      </div>
      <el-row>
        <el-col :span="24">
          <el-card class="admin-info">
            <div slot="header" class="clearfix">
              <span>当前管理员信息</span>
            </div>
            <!-- 使用 el-row 和 el-col 实现一行两列布局 -->
            <el-row class="info-row">
              <el-col :span="12" class="info-col">
                <el-descriptions
                  title="基本信息"
                  :column="1"
                  border
                  class="info-descriptions"
                  size="medium"
                >
                  <el-descriptions-item label="用户名">{{
                    adminInfo.username
                  }}</el-descriptions-item>
                  <el-descriptions-item label="昵称">{{
                    adminInfo.nickname
                  }}</el-descriptions-item>
                </el-descriptions>
              </el-col>
              <el-col :span="12" class="info-col">
                <el-descriptions
                  title="其他信息"
                  :column="1"
                  border
                  class="info-descriptions"
                  size="medium"
                >
                  <el-descriptions-item label="头像">
                    <el-avatar
                      :src="adminInfo.avatar"
                      shape="square"
                      size="small"
                    ></el-avatar>
                  </el-descriptions-item>
                  <el-descriptions-item label="角色">{{
                    adminInfo.role
                  }}</el-descriptions-item>
                </el-descriptions>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-card class="password-change">
            <div slot="header" class="clearfix">
              <span>修改信息</span>
            </div>
            <el-tabs v-model="activeTab" tab-position="top">
              <el-tab-pane label="修改昵称" name="nickname">
                <el-form
                  ref="nicknameForm"
                  :model="nicknameForm"
                  :rules="nicknameRules"
                  label-width="120px"
                >
                  <el-form-item label="新昵称" prop="nickname">
                    <el-input
                      v-model="nicknameForm.nickname"
                      placeholder="请输入新昵称"
                    ></el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="updateNickname"
                      >修改昵称</el-button
                    >
                  </el-form-item>
                </el-form>
              </el-tab-pane>
              <el-tab-pane label="修改头像" name="avatar">
                <el-upload
                  class="avatar-uploader"
                  action="/admin/file/upload"
                  name="file"
                  :data="uploaddata"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                >
                  <img v-if="avatarUrl" :src="avatarUrl" class="avatar" />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
                <el-button
                  type="primary"
                  @click="updateAvatar"
                  :disabled="!avatarUrl"
                  >修改头像</el-button
                >
              </el-tab-pane>
              <el-tab-pane label="修改密码" name="password">
                <el-form
                  ref="passwordForm"
                  :model="passwordForm"
                  :rules="passwordRules"
                  label-width="120px"
                >
                  <el-form-item label="新密码" prop="newPassword">
                    <el-input
                      v-model="passwordForm.newPassword"
                      type="password"
                      placeholder="请输入新密码"
                      show-password
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="确认新密码" prop="confirmPassword">
                    <el-input
                      v-model="passwordForm.confirmPassword"
                      type="password"
                      placeholder="请再次输入新密码"
                      show-password
                    ></el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="changePassword"
                      >修改密码</el-button
                    >
                  </el-form-item>
                </el-form>
              </el-tab-pane>
            </el-tabs>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import { mapActions, mapGetters } from "vuex";

export default {
  name: "AdminManagement",
  data() {
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.passwordForm.newPassword) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };
    return {
      adminInfo: {
        username: "admin123",
        nickname: "管理员A",
        avatar: require("@/assets/logo.png"), // 默认头像
        role: "区域管理员",
        adminId: "",
        password: "",
        roleId: "",
      },
      uploaddata: {
        entityId: "",
        entityType: "adminAvatar",
      },
      activeTab: "nickname", // 默认激活的标签页
      nicknameForm: {
        nickname: "",
      },
      nicknameRules: {
        nickname: [
          { required: true, message: "请输入新昵称", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "昵称长度为2到10个字符",
            trigger: "blur",
          },
        ],
      },
      avatarUrl: "", // 临时存储上传的头像地址
      passwordForm: {
        newPassword: "",
        confirmPassword: "",
      },
      passwordRules: {
        newPassword: [
          { required: true, message: "请输入新密码", trigger: "blur" },
          { min: 6, message: "密码长度不能少于6位", trigger: "blur" },
        ],
        confirmPassword: [
          { required: true, message: "请再次输入新密码", trigger: "blur" },
          { validator: validateConfirmPassword, trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    ...mapGetters({
      adminData: "admin/getAdmin",
    }),
  },
  mounted() {

    if (!this.checkAdminData()) return;
    try {
      this.setAdminInfo();
      this.setUploadData();
    } catch (error) {
      this.handleDataError(error);
    }
  },
  methods: {
    ...mapActions({
      setNickName: "admin/ADMIN_SET_NICK_NAME",
      setAvatar: "admin/ADMIN_SET_AVATAR",
      setPassword: "admin/ADMIN_SET_PASSWORD",
    }),
    // 检查管理员数据是否存在
    checkAdminData() {
      if (!this.adminData) {
        this.$message.error("尚未登录");
        this.$router.push({ name: "Home" });
        return false;
      }
      return true;
    },
    // 设置管理员信息
    setAdminInfo() {
      const {
        username = "未知用户",
        nickname = "暂时没有昵称哦",
        avatarUrl,
        roleId,
        password,
        adminId,
      } = this.adminData;

      this.adminInfo = {
        username,
        nickname,
        avatar: avatarUrl || require("@/assets/logo.png"),
        role: this.statusRole(roleId),
        roleId,
        password,
        adminId,
      };
    },
    // 设置上传数据
    setUploadData() {
      this.uploaddata = {
        entityId: this.adminInfo.adminId,
        entityType: "adminAvatar",
      };
    },
    // 处理数据错误
    handleDataError(error) {
      console.error("解析用户数据失败", error);
      this.$message.error("用户数据异常，请重新登录");
      this.$router.push({ name: "Home" });
    },
    statusRole(i) {
      switch (i) {
        case 3:
          return "商店管理员";
        case 4:
          return "区域管理员";
        case 5:
          return "超级管理员";
        default:
          this.$message({
            showClose: true,
            message: "错误角色",
            type: "error",
          });
          this.$router.push({ name: "Home" });
      }
    },
    updateNickname() {
      this.$refs.nicknameForm.validate((valid) => {
        if (!valid) {
          this.$message.error("表单验证失败，请检查输入内容");
          return;
        }

        const updateData = {
          adminId: this.adminInfo.adminId,
          nickname: this.nicknameForm.nickname,
        };
        this.setNickName(updateData)
          .then((res) => {
            // console.log(res.data.nickname);
            this.adminInfo.nickname = res.data.nickname;
            this.$message.success("更新成功！");
            console.log(this.adminInfo.nickname);
          })
          .catch((err) => {
            console.log("异常", err.message);
          })
          .finally(() => {
            this.nicknameForm.nickname = "";
          });
      });
    },
    updateAvatar() {
      if (this.avatarUrl) {
        this.adminInfo.avatar = this.avatarUrl;
        this.$message.success("头像修改成功！");
        this.avatarUrl = ""; // 清空临时头像地址
      }
    },
    handleAvatarSuccess(response, file) {
      const fileUrl = response.data.fileUrl;
      this.avatarUrl = URL.createObjectURL(file.raw);
      const updateData = {
        adminId: this.adminInfo.adminId,
        avatarUrl: fileUrl,
      };
      console.log(updateData)
      this.setAvatar(updateData)
        .then(() => {
          this.avatarUrl = fileUrl;
          this.adminInfo.avatar = this.avatarUrl;
        })
        .catch((err) => {
          console.log("异常", err.message);
        })
        .finally(() => {});
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPNG) {
        this.$message.error("上传头像图片只能是 JPG 或 PNG 格式！");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB！");
      }
      return (isJPG || isPNG) && isLt2M;
    },
    changePassword() {
      this.$refs.passwordForm.validate((valid) => {
        if (!valid) {
          this.$message.error("表单验证失败，请检查输入内容");
          return;
        }

        const updateData = {
          adminId: this.adminInfo.adminId,
          password: this.passwordForm.newPassword,
        };

        this.setPassword(updateData)
          .then((res) => {
            this.adminInfo.password = res.data.password;

            this.$message.success("修改成功");
          })
          .catch((err) => {
            console.error("异常", err);
            // this.$message.error("网络错误或服务器异常");
          })
          .finally(() => {
            this.passwordForm.newPassword = "";
            this.passwordForm.confirmPassword = "";
          });
      });
    },
  },
};
</script>

<style scoped>
.admin-management {
  padding: 20px;
  background-color: #f0f2f5;
}

.box-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

.info-row {
  display: flex;
  align-items: stretch; /* 确保两列高度一致 */
}

.info-col {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.info-descriptions {
  flex: 1; /* 让描述框填满整个列的高度 */
  margin: 0 10px;
}

.avatar-uploader {
  text-align: center;
  margin-bottom: 20px;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
}

.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-button {
  margin-top: 10px;
}
</style>